"""
光照数据采集与收集

MQTT接收光照传感器数据
"""

import paho.mqtt.client as mqtt
import os

# MQTT服务器地址
broker_address = "192.168.10.29"  # 替换为你的MQTT代理地址
port = 1883  # MQTT代理的端口，默认为1883
client_id = "light_mqtt_client"  # MQTT客户端的唯一ID，不冲突即可

# 收集 train valid test数据集
dataset_type = "test"
# 定义当前亮度值的类别,比如室内、暗室、强光、室内侧光
dataset_category = "sun"

light_data_url = "./datasets/{}/light_{}.txt".format(dataset_type, dataset_category)

light_data_file = open(light_data_url, "a+")

# 当连接到MQTT代理时调用的回调函数
def on_connect(client, userdata, flags, reason_code, properties):
    print(f"Connected with result code {reason_code}")
    # 订阅主题
    client.subscribe("base/light")


# 当接收到MQTT消息时调用的回调函数
def on_message(client, userdata, msg):
    light = msg.payload.decode('utf-8')
    print(light)
    light_data_file.write(f"{light}\n")
    light_data_file.flush()


# 创建MQTT客户端实例
client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2)

# 为客户端设置回调函数
client.on_connect = on_connect
client.on_message = on_message

# 连接到MQTT代理
client.connect(broker_address, port)

# 开始网络循环，处理接收到的消息和重连
client.loop_forever()
